#-*- coding: utf-8 -*-
import pygtk
pygtk.require('2.0')
import gtk
import pango
from usagi.kanji import Kanji
from usagi.paths import ICON_PATH
from usagi.tango import Word

class UsagiWindow(gtk.Window):
    def __init__(self,app,cur):
        gtk.Window.__init__(self)
        self.set_icon_from_file(ICON_PATH)
        self.app = app
        self.cur=cur
        self.connect("delete_event", self.delete_event)  
        self.kanji= None
        
        self.vbox= gtk.VBox(False, 0)
        self.add(self.vbox)

        #Next
        self.next = gtk.Button(u"Tsugi",gtk.STOCK_GO_FORWARD)
        self.next.get_children()[0].get_children()[0].get_children()[1].set_text(u"次ぎ")
        self.next.connect("clicked", self.button, "next")
        self.vbox.pack_start(self.next)

        #Kanji frame
        self.kanjiframe=gtk.Frame(u"漢字")
        self.vbox.pack_start(self.kanjiframe)
        self.kanjilab = gtk.Label()
        jap_font = pango.FontDescription ("normal 60")
        self.kanjilab.modify_font (jap_font)
        self.kanjiframe.add(self.kanjilab)

        #Jouhou frame
        self.jouhouframe=gtk.Frame(u"情報")
        self.vbox.pack_start(self.jouhouframe)
        self.jouhoulab=gtk.Label()
        self.jouhouframe.add(self.jouhoulab)

        #Nanori frame
        self.nanoriframe=gtk.Frame(u"名乗り")
        self.vbox.pack_start(self.nanoriframe)
        self.nanorilab = gtk.Label()
        self.nanoriframe.add(self.nanorilab)
        
        #Onyomi frame
        self.onyomiframe=gtk.Frame(u"音読み")
        self.vbox.pack_start(self.onyomiframe)
        self.onyomilab = gtk.Label()
        self.onyomiframe.add(self.onyomilab)

        #Kunyomi frame
        self.kunyomiframe=gtk.Frame(u"訓読み")
        self.vbox.pack_start(self.kunyomiframe)
        self.kunyomilab = gtk.Label()
        self.kunyomiframe.add(self.kunyomilab)

        #Imi frame
        self.imiframe=gtk.Frame(u"意味")
        self.vbox.pack_start(self.imiframe)
        self.imilab = gtk.Label()
        self.imiframe.add(self.imilab)

        #Horizontal buttons
        self.hbox = gtk.HBox(False,0)
        self.vbox.pack_end(self.hbox)
        self.practice = gtk.Button(None,gtk.STOCK_JUSTIFY_FILL)
        self.practice.get_children()[0].get_children()[0].get_children()[1].set_text(u"練習")
        self.practice.connect("clicked", self.button, "practice")
        self.addbtn = gtk.Button(None,gtk.STOCK_ADD)
        self.addbtn.get_children()[0].get_children()[0].get_children()[1].set_text(u"追加")
        self.addbtn.connect("clicked", self.button, "add")
        self.hbox.pack_start(self.practice,False)
        self.hbox.pack_start(self.addbtn)

        #Use this later
        self.yomikomi = gtk.Label(u"読み込み中...")

        #...lights on: 
        self.show_all()



    def button(self,widget,data):
        if data=='next':
            self.set_kanji(self.cur.fetch_kanji())
        elif data=='add':
            self.remove(self.get_children()[0])
            self.add(self.yomikomi)            
            self.yomikomi.show()
            while gtk.events_pending():
		        gtk.main_iteration()
            self.app.master_kanji(str(self.kanji))
            self.remove(self.get_children()[0])
            self.add(self.vbox)
        elif data=='practice':
            self.hide_all()
            while gtk.events_pending():
		        gtk.main_iteration()
            self.app.renshuutime()

    def infotext(self):
        orna=lambda i: i and str(i) or "N/A"
        data=(self.kanji.bushu, orna(self.kanji.S), orna(self.kanji.G),\
              orna(self.kanji.J), orna(self.kanji.F))
        l1=u"部首: %s\t画数: %s画\t常用漢字: 第%s学年\n" % data[:3]
        l2=u"日本語能力試験: %s級\t出現頻度:%s" % data[3:]
        return l1+l2

    def set_kanji(self,kanji):
        kanji=Kanji(kanji)
        self.kanji = kanji
        self.set_title(u"兎先生::%s"%str(kanji))
        self.kanjilab.set_text(str(kanji))
        self.jouhoulab.set_text(self.infotext())
        self.onyomilab.set_text(kanji.onyomi and ", ".join(kanji.onyomi) or "N/A")
        self.kunyomilab.set_text(kanji.kunyomi and ", ".join(kanji.kunyomi) or "N/A")
        self.imilab.set_text(kanji.meaning and ", ".join(kanji.meaning) or "N/A")
        self.nanorilab.set_text(kanji.nanori and ", ".join(kanji.nanori) or "N/A")

    def delete_event(self,w,e=None,d=None):
        gtk.main_quit()
        print "Keep that in mind..."
        return False

    def main(self, kanji):
        self.set_kanji(kanji)
        gtk.main()

class ScrollMess(gtk.Dialog):
    def __init__(self, title=None, parent=None, message="",text=""):
        gtk.Dialog.__init__(self,title,parent,0,(gtk.STOCK_OK,gtk.RESPONSE_OK))
        self.vbox.pack_start(gtk.Label(message),False)
        textarea = gtk.TextView()
        textarea.set_editable(False)
        textarea.set_overwrite(False)
        #textarea.set_sensitive(False)
        sw = gtk.ScrolledWindow()
        sw.add(textarea)
        sw.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC)
        textarea.get_buffer().set_text(text)
        self.vbox.pack_start(sw)
        
    def showanddie(self):
        self.show_all()
        if self.run() == gtk.RESPONSE_OK:
            self.destroy()

class NewWords(ScrollMess):
    def __init__(self,title=None, parent=None, message="", text=""):
        self.words=text.split('\n')
        ScrollMess.__init__(self,title,parent,message,text)
        btn = gtk.Button("Export")
        btn.show()
        btn.connect("clicked", self.export)
        self.vbox.pack_start(btn)

    def export(self,w=None):
        file_save = gtk.FileChooserDialog(title=None, action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))

        if file_save.run() == gtk.RESPONSE_OK:
            result=file_save.get_filename()
            dock=open(result,'w')
            for i in self.words:
                eWord=Word(i)
                for j in eWord.interpretations:
                    dock.write(i+"\t"+j[0]+"\t"+"|".join(j[-1])+"\n")
            dock.close()
            print "Saved words with tab separated fields as %s"%result
        file_save.destroy()

            
            
